<?php


namespace app\api\service\activity_order;


use app\api\model\SjActivity;
use app\api\model\SjActivityItem;
use app\api\model\SjActivityOrder;
use app\api\model\SjActivityOrderItem;
use app\api\service\Token;
use app\lib\exception\ParameterException;
use think\Db;
use think\Exception;
use think\facade\Log;

class CreateSjOrder extends Token
{
    /**
     * 商家活动上车操作
     * 1. 判断队伍是否已满
     * 2. 是否已报名
     * 3. 创建信息
     * 4. 返回支付number
     */

    // 活动
    protected $sjActivity;

    // 用户
    protected $user;

    // 星期数
    protected $week;

    // 日期
    protected $date;

    // 子项ID
    protected $sjActivityItem;

    // 结算数量
    protected $number;

    // 类型
    protected $type;

    function __construct($id, $week, $sjActivityItemId,$number,$date,$type){
        $this->sjActivity = SjActivity::where('id',$id)
            ->with('imgs.img,items')->find();
        $this->week = $week;
        $this->sjActivityItem = SjActivityItem::get($sjActivityItemId);
        $this->number = $number;
        $this->date = $date;
        $this->type = $type;
    }

    /**
     * 入口方法
     */
    public function entrance()
    {
        $this->user = self::judgeUser();
        return $this->judgeData();
    }

    /**
     * 判断数据
     */
    protected function judgeData()
    {
        $time = time();
        if($this->number < 1) {
            throw new ParameterException([
                'msg' => [
                    'order' => '请重新选择人数'
                ]
            ]);
        }
        $week_data = explode('-',$this->sjActivity['week_data']);
        $status = false;
        foreach ($week_data as $v) {
            if($v == $this->week) {
                $status = true;
            }
        }
        if(!$status) {
            throw new ParameterException([
                'msg' => [
                    'order' => '当天没有活动'
                ]
            ]);
        }
        if(!$this->sjActivityItem) {
            throw new ParameterException([
                'msg' => [
                    'order' => '请选择时间'
                ]
            ]);
        }
        $date = date('Y-m-d');
        if($date == $this->date) {
            $this->sjActivityItem = SjActivityItem::get($this->sjActivityItem['id']);
            $end_time = $date.' '.$this->sjActivityItem['end_time'].':00';
            if($time > strtotime($end_time)) {
                throw new ParameterException([
                    'msg' => [
                        'order' => '该时间段活动已经结束'
                    ]
                ]);
            }
        }
        $info = SjActivityOrder::where('activity_id',$this->sjActivity['id'])
            ->where('activity_item_id',$this->sjActivityItem['id'])->find();
        if($info) {
            if($info['status'] == 2) {
                throw new ParameterException([
                    'msg' => [
                        'order' => '已申请该活动'
                    ]
                ]);
            }else{
                return ['out_trade_no'=>$info['out_trade_no']];
            }
        }
        if($this->sjActivity['num_status'] > 0){
            $where[] = ['activity_id', 'eq', $this->sjActivity['id']];
            $where[] = ['activity_item_id', 'eq', $this->sjActivityItem['id']];;
            $where[] = ['end_time', 'gt', $time];
            $where[] = ['status', 'eq', 1];
            $whereOne[] = ['activity_id', 'eq', $this->sjActivity['id']];
            $whereOne[] = ['activity_item_id', 'eq', $this->sjActivityItem['id']];
            $whereOne[] = ['status', 'gt', 1];
            if($this->sjActivity['num_status'] == 2) {
                if($this->user['gender'] == 3) {
                    throw new ParameterException([
                        'msg' => [
                            'order' => '请点击头像进入更改性别'
                        ]
                    ]);
                }
                $where[] = ['gender', 'eq', $this->user['gender']];
            }
            $count = SjActivityOrder::where($where)->count();
            $count_one = SjActivityOrder::where($whereOne)->count();
            $count = $count + $count_one + 1;
            if($this->sjActivity['num_status'] == 1) {
                if($count > $this->sjActivity['number']) {
                    throw new ParameterException([
                        'msg' => [
                            'order' => '报名人数已满'
                        ]
                    ]);
                }
            } elseif($this->sjActivity['num_status'] == 2) {
                if($this->user['gender'] == 1) {
                    if($count > $this->sjActivity['man_num']) {
                        throw new ParameterException([
                            'msg' => [
                                'order' => '报名人数已满'
                            ]
                        ]);
                    }
                } elseif($this->user['gender'] == 2) {
                    if($count > $this->sjActivity['women_num']) {
                        throw new ParameterException([
                            'msg' => [
                                'order' => '报名人数已满'
                            ]
                        ]);
                    }
                }
            }
        }
        return $this->createData();
    }

    /**
     * 创建订单
     */
    protected function createData()
    {
        Log::init([
            'type' => 'File'
        ]);
        Db::startTrans();
        try {
            $time = time();
            $mode = SjActivityOrder::create([
                'openid' => $this->user['openid'],
                'price' => $this->sjActivity['price']*$this->number,
                'order_no' => makeOrderNo(),
                'status' => 1,
                'end_time' => $time + 1800,
                'activity_id' => $this->sjActivity['id'],
                'activity_msg' => json_encode($this->sjActivity),
                'activity_item_id' => $this->sjActivityItem['id'],
                'activity_item_msg' => json_encode($this->sjActivityItem),
                'number' => $this->number,
                'date_str' => $this->date,
                'week_str' => $this->week,
                'type' => $this->type,
                'gender' => $this->user['gender'],
            ]);
            $mode->out_trade_no = '4t2021'.$mode->id;
            $mode->save();
            for ($i=0;$i< $this->number;$i++ ){
               SjActivityOrderItem::create([
                   'order_id' => $mode->id,
                   'status' => 1
               ]);
            }
            Db::commit();
            return [
                'out_trade_no' => '4t2021'.$mode->id
            ];
        }
        catch (Exception $e){
            Db::rollback();
            Log::write('创建商家活动订单:'.$e,'error');
            throw new ParameterException([
                'msg' => [
                    'order' => '订单创建失败'
                ]
            ]);
        }
    }
}